package com.xgst.land.activity.check

import android.animation.ValueAnimator
import android.bluetooth.BluetoothManager
import android.graphics.Color
import android.os.CountDownTimer
import android.view.View
import android.view.animation.AccelerateDecelerateInterpolator
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.GridLayoutManager
import androidx.viewpager2.adapter.FragmentStateAdapter
import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.SpanUtils
import com.blankj.utilcode.util.TimeUtils
import com.blankj.utilcode.util.UiMessageUtils
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.listener.OnItemClickListener
import com.githang.statusbar.StatusBarCompat
import com.google.android.material.tabs.TabLayout
import com.gym.baselib.base.BaseActivity
import com.ht.medicaltreatment.serial.SerialPortUtils
import com.xgst.land.R
import com.xgst.land.bean.LandUIDBean
import com.xgst.land.bean.MessageScanBean
import com.xgst.land.databinding.ActivityInventoryScallLayoutBinding
import com.xgst.land.dialog.ReplaceDialog
import com.xgst.land.fragment.ScanQueryFragment
import com.xgst.land.fragment.ScanResultFragment
import com.xgst.land.utils.MessageKey
import com.xgst.land.utils.SoundUtils
import com.xgst.land.utils.runOnMain
import com.xgst.land.viewmodel.PDScanViewModel
import java.text.SimpleDateFormat
import java.util.Timer
import kotlin.concurrent.schedule

/**
 * 盘点-开始盘点- 横屏
 */
class InventoryScanLandActivity : BaseActivity<ActivityInventoryScallLayoutBinding>(), UiMessageUtils.UiMessageCallback,
    OnItemClickListener {
    // 300833b2ddd9014000000070   000000000000319ac502b086
    private lateinit var mViewModel:PDScanViewModel
    private var valueAnimator:ValueAnimator? = null
    //盒子的UID
    private lateinit var mBoxUid:String
    private var transportSampleBoxId = ""
    private lateinit var scanAdapter: PDScanLandAdapter
    //表格集合
    private val list = mutableListOf<LandUIDBean>()

    companion object{
        //用来记录每个uid的位置
        val mUidMap = mutableMapOf<String,LandUIDBean>()
    }
    private lateinit var dialog : ReplaceDialog
    private var isReplace = false
    //通过名称记录bean
    val mNameMap = mutableMapOf<String,LandUIDBean>()
    private var orderId = 0
    private lateinit var bluetoothManager:BluetoothManager

    private var boxCol = 0
    private var boxRow = 0

    private var downTimeCount = 10
    private lateinit var fragments:Array<Fragment>
    private lateinit var resultFragment: ScanResultFragment
    private lateinit var queryFragment: ScanQueryFragment
    private lateinit var downTimer:CountDownTimer

    override fun viewBinding(): ActivityInventoryScallLayoutBinding {
        return ActivityInventoryScallLayoutBinding.inflate(layoutInflater)
    }

    override fun init() {
        mViewModel = ViewModelProvider(this)[PDScanViewModel::class.java]
        StatusBarCompat.setStatusBarColor(this,getColor(R.color.white),true)
        bluetoothManager = getSystemService(BLUETOOTH_SERVICE) as BluetoothManager
        //进来就开始盘存 节约时间
        SerialPortUtils.startUHF()
        downTimer = object : CountDownTimer(10*1000,1000){
            override fun onTick(time: Long) {
                downTimeCount--
            }

            override fun onFinish() {

            }
        }.start()

        dialog = ReplaceDialog(this)
        mBoxUid = intent.getStringExtra("uid")?:""

        orderId = intent.getIntExtra("orderId",0)
        scanAdapter = PDScanLandAdapter()

        val tab1 = binding.tabLayout.newTab()
        tab1.setText("盘点结果")
        binding.tabLayout.addTab(tab1)

        val tab2 = binding.tabLayout.newTab()
        tab2.setText("查询样本")
        binding.tabLayout.addTab(tab2)
        resultFragment = ScanResultFragment()
        queryFragment = ScanQueryFragment()
        fragments = arrayOf(resultFragment,queryFragment)

        binding.viewPager.adapter = object : FragmentStateAdapter(this){
            override fun getItemCount() = fragments.size
            override fun createFragment(position: Int) = fragments[position]
        }

        initData(false)
        initClick()

        initListener()
    }

    /**
     * 获取数据
     */
    private fun initData(isReset:Boolean) {
        showProgress()
        mViewModel.scanData(mBoxUid, "$orderId", {
            boxCol = it.rfidSampleBox.sampleBoxStru.structureCol
            boxRow = it.rfidSampleBox.sampleBoxStru.structureRow

            binding.recyclerView.layoutManager = GridLayoutManager(this@InventoryScanLandActivity, boxCol)
            binding.recyclerView.adapter = scanAdapter
            //转运样本盒id
            transportSampleBoxId  = "${it.inventorySampleBox.id}"
            //binding.tvTitleInfo.text = "实际盘点样本信息：${it.rfidSampleBox.name}"
            list.clear()
            mUidMap.clear()
            mNameMap.clear()
            it.rfidSampleBox.rfidSampleVOList?.forEach {
                /**
                 * 样本盒中，有些孔位有试管，有些孔位没有试管。it.uid为空，就是没有试管的
                 * list集合的目的是按照行 列 把adapter填充满，正常都是白色
                 * 如果有uid的，颜色是蓝色，这样一个样本盒就出来了。
                 */
               val bean = LandUIDBean(
                    originalLocation = it.location,
                    originalUid = it.uid,
                    rfidSampleId = it.rfidSampleId,
                    type = 0,
                    name = it.name)
                list += bean
                mUidMap.put(it.uid!!,bean)
                val nameSpit = it.name.split("-")
                if(nameSpit.size > 2){
                    val key = "${nameSpit[nameSpit.size-2]}-${nameSpit[nameSpit.size-1]}"
                    mNameMap.put(key,bean)
                }
            }
            resultFragment.setOriginalCount(mUidMap.size)
            scanAdapter.setNewInstance(list)
            dismissProgress()
            if(isReset){
                //重新核验
                //startScan()
                SerialPortUtils.startUHF()
                startProgress(false)
            }
        })
    }

    private fun initClick() {

        dialog.setOnDismissListener {5
            binding.btnStopScan.text = "开始扫描"
        }

        //确认
        binding.btnPositive.setOnClickListener {
            if(!resultFragment.isSubmit()){
                showToast("盘点检验有误")
                return@setOnClickListener
            }
            showProgress()
            mViewModel.submit(transportSampleBoxId,{
                dismissProgress()
                showToast("提交成功")
                binding.btnPositive.text = "已提交"
                binding.btnPositive.isEnabled = false
                binding.btnPositive.setBackgroundColor(getColor(R.color.color97))

                binding.btnAgain.isEnabled = false
                binding.btnAgain.setBackgroundColor(getColor(R.color.color97))

                setResult(RESULT_OK)
                finish()
            },{
                dismissProgress()
                showToast(it)
            })
        }

        //重新核验
        binding.btnAgain.setOnClickListener {
            scanCount = 0
            reset()
        }

        // 开始盘点
        binding.btnStopScan.setOnClickListener {
            if(scanCount == 0){
                startScan()
            }else{
                scanCount = 0
                reset()
            }
            //startScan()
        }
    }

    fun startScan(isReplace:Boolean = false) {
        this.isReplace = isReplace
        if(!isReplace){
            binding.btnStopScan.text = "启动扫描中..."
        }
        if(downTimeCount <= 0){
            SerialPortUtils.checkData()
        }else{
            startProgress(true)
        }
    }

    //查询
    fun locationUID(namesList:MutableList<String>){
        scanAdapter.data.forEachIndexed { index, landUIDBean ->
            if(landUIDBean.query){
                landUIDBean.query = false
                scanAdapter.notifyItemChanged(index)
            }
        }

        scanAdapter.data.forEach {bean ->
            namesList.forEach {queryBean ->
                if(bean.name!!.contains(queryBean)){
                    bean.query = true
                }
            }
        }
        scanAdapter.notifyDataSetChanged()
        /*namesList.forEach {
            if(mNameMap.containsKey(it)){
                val bean = mNameMap.get(it)!!
                bean.query = true
                scanAdapter.notifyItemChanged(bean.originalLocation-1)
            }
        }*/

    }

    fun setScanState(state:Boolean){
        if(state){
            binding.tvScanState.text = "识别状态：正常"
            binding.tvScanState.setTextColor(getColor(R.color.green))
        }else{
            binding.tvScanState.text = "识别状态：异常"
            binding.tvScanState.setTextColor(getColor(R.color.red))
        }
    }

    private var scanCount = 0
    /**
     * 扫描结果
     */
    private fun initListener() {
        UiMessageUtils.getInstance().addListener(MessageKey.SCAN_ID,this)

        binding.tabLayout.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener{
            override fun onTabSelected(tab: TabLayout.Tab?) {
                if(tab?.text == "盘点结果"){
                    binding.viewPager.setCurrentItem(0,false)
                    binding.btnPositive.visibility = View.VISIBLE
                }else{
                    binding.viewPager.setCurrentItem(1,false)
                    binding.btnPositive.visibility = View.GONE
                }
            }

            override fun onTabUnselected(tab: TabLayout.Tab?) {

            }

            override fun onTabReselected(tab: TabLayout.Tab?) {

            }
        })

        scanAdapter.setOnItemClickListener(this)
    }

    //处理扫描出来的UID
    fun checkUID(newUID:String,position:Int){
        if(isReplace){
            resultFragment.replace(newUID)
            return
        }
        if(position > scanAdapter.data.size){
            return
        }
        SoundUtils.playSound(SoundUtils.SOUND_SUCCESS)
        val value = mUidMap[newUID]
        val bean = scanAdapter.getItem(position-1)
        bean.newUid = newUID
        bean.newLocation = position
        bean.type = 1
        scanAdapter.notifyItemChanged(position-1)

        if(value == null){
            //不是这个样本盒内的管子
            //errorList += newUID!!
            //resultFragment.setMoreCount(errorList.size)
        }
    }

    private fun reset() {
        resultFragment.reset()
        queryFragment.reset()
        isReplace = false
        initData(true)
    }


    override fun handleMessage(localMessage: UiMessageUtils.UiMessage) {
        if(!ActivityUtils.getTopActivity().localClassName.contains("InventoryScanLandActivity")){
            return
        }
        val bean = localMessage.`object` as MessageScanBean
        if(bean.uid.isNotEmpty()){
            scanCount++
            binding.btnStopScan.text = "盘点中：$scanCount/${boxCol*boxRow}"
            if(bean.row != 0 && bean.col != 0){
                val position = ((bean.row-1) * boxCol) + bean.col
                //LogUtils.i("${TimeUtils.getNowString(SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSSSS"))} 扫描到UID  :  ${bean.uid}    row行:${bean.row}    col列:${bean.col}     position:$position")
                checkUID(bean.uid,position)
            }else{
               // LogUtils.i("${TimeUtils.getNowString(SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSSSS"))} 扫描到UID信息不全  :  ${bean.uid}    row行:${bean.row}    col列:${bean.col}")
            }
        }else{
            binding.btnStopScan.text = "重新核验"
            binding.btnStopScan.isEnabled = true
            //没有数据了，开始计算结果
            resultFragment.checkScanResult(scanAdapter.data)
            scanAdapter.data.forEachIndexed { index, landUIDBean ->
                if(landUIDBean.type == 0){
                    landUIDBean.type = 1 //type:1 已盘点
                    scanAdapter.notifyItemChanged(index)
                }
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        UiMessageUtils.getInstance().removeListener(this)
    }

    override fun onItemClick(adapter: BaseQuickAdapter<*, *>, view: View, position: Int) {
        //试管点击
        val item = adapter.data[position] as LandUIDBean
        binding.tvUIDName.visibility = View.VISIBLE
        if(item.originalUid  != item.newUid && item.newUid != null && item.originalUid != null){
            //位置错误了
            resultFragment.getErrorLocationList().forEach {
                if(item.newUid == it.newUid){
                    val location = mUidMap[item.newUid]?.originalLocation
                    val pre = "孔位【${item.newLocation}】当前识别到的样本为：${item.name}，"
                    SpanUtils.with(binding.tvUIDName)
                        .append(pre)
                        .append("该样本应位于孔位：$location")
                        .setForegroundColor(Color.RED)
                        .create()
                }
            }
        }else if(item.originalUid != null && item.newUid == null){
            binding.tvUIDName.text = "样本缺失：${item.name}"
        }else if(item.originalUid == null && item.newUid != null){
            //原本是空的，现在有试管了，多余的
            binding.tvUIDName.text = "多余的试管：${item.name}"
        }else{
            binding.tvUIDName.text = "${item.name}"
        }
        Timer().schedule(4000){
            runOnMain {
                binding.tvUIDName.visibility = View.GONE
            }
        }
    }

    fun startProgress(isClickStartScan:Boolean){
        valueAnimator?.cancel()
        binding.flProgress.visibility = View.VISIBLE
        valueAnimator = ValueAnimator.ofInt(0, 100)
        valueAnimator?.let {
            it.addUpdateListener { animator ->
                val currentValue = animator.animatedValue as Int
                binding.progressBar.percent = currentValue.toFloat()
                if(isClickStartScan && downTimeCount <= 0){
                    it.cancel()
                    binding.flProgress.visibility = View.GONE
                    SerialPortUtils.checkData()
                }else if(currentValue >= 100){
                    binding.flProgress.visibility = View.GONE
                    SerialPortUtils.checkData()
                }
            }
            it.duration = 10*1000
            it.start()
        }
    }
}